package com.atguigu.chapter08;

import com.atguigu.bean.HotItem;
import com.atguigu.bean.UserBehavior;
import com.atguigu.util.AnqclnUtil;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.AggregateFunction;
import org.apache.flink.api.common.state.ListState;
import org.apache.flink.api.common.state.ListStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;
import java.util.Comparator;
import java.util.List;

/**
 * Author: Pepsi
 * Date: 2023/8/14
 * Desc:
 */
public class Flink04_Project_High_TopN {
    public static void main(String[] args) {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 1000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(2);

        env
                .readTextFile("input/UserBehavior.csv")
                .map(line -> {
                    String[] data = line.split(",");
                    return new UserBehavior(
                            Long.valueOf(data[0]),
                            Long.valueOf(data[1]),
                            Integer.valueOf(data[2]),
                            data[3],
                            // valueOf和parseLong的区别是返回值类型，前面是包装类，后面是long，建议分开用，减少自动装箱拆箱的性能浪费
                            Long.parseLong(data[4])
                    );
                })
                .filter(ub -> "pv".equals(ub.getBehavior()))
                // 分配时间戳和水印
                .assignTimestampsAndWatermarks(
                        WatermarkStrategy
                                // 乱序程度为3s
                                .<UserBehavior>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                                // 指定时间戳  ，对象里面的时间戳是秒，转成毫秒
                                .withTimestampAssigner((element, recordTimestamp) -> element.getTimestamp() * 1000)
                )
                // 先按照商品的itemid分组
                .keyBy(UserBehavior::getItemId)
                // 分完组后，开窗做聚合
                .window(TumblingEventTimeWindows.of(Time.hours(1)))
                .aggregate(new AggregateFunction<UserBehavior, Long, Long>() {
                               @Override
                               public Long createAccumulator() {
                                   return 0L;
                               }

                               @Override
                               public Long add(UserBehavior value, Long accumulator) {
                                   return accumulator + 1;
                               }

                               @Override
                               public Long getResult(Long accumulator) {
                                   return accumulator;
                               }

                               @Override
                               public Long merge(Long a, Long b) {
                                   return null;
                               }
                           },
                        new ProcessWindowFunction<Long, HotItem, Long, TimeWindow>() {
                            @Override
                            public void process(Long aLong,
                                                Context context,
                                                Iterable<Long> elements,
                                                Collector<HotItem> out) throws Exception {
                                HotItem hotItem = new HotItem(aLong, context.window().getEnd(), elements.iterator().next());
                                out.collect(hotItem);
                            }
                        }
                )
                .keyBy(HotItem::getWEnd)
                .process(new KeyedProcessFunction<Long, HotItem, String>() {

                    private ListState<HotItem> hotItemState;

                    @Override
                    public void onTimer(long timestamp,
                                        OnTimerContext ctx,
                                        Collector<String> out) throws Exception {

                        List<HotItem> hotItemList = AnqclnUtil.toList(hotItemState.get());
                        hotItemList.sort(new Comparator<HotItem>() {
                            @Override
                            public int compare(HotItem o1, HotItem o2) {
                                return o2.getCount().compareTo(o1.getCount());
                            }
                        });
                        String msg = "\n-----------\n";
                        for (int i = 0; i < Math.min(hotItemList.size(),3); i++) {
                            HotItem hotItem = hotItemList.get(i);
                            msg+=hotItem+"\n";
                        }
                        out.collect(msg);
                    }

                    @Override
                    public void open(Configuration parameters) throws Exception {
                        hotItemState = getRuntimeContext().getListState(new ListStateDescriptor<HotItem>("HotItemState", HotItem.class));
                    }

                    @Override
                    public void processElement(HotItem value,
                                               Context ctx,
                                               Collector<String> out) throws Exception {
                        if (!hotItemState.get().iterator().hasNext()) {
                            ctx.timerService().registerEventTimeTimer(value.getWEnd() + 2000);
                        }
                        hotItemState.add(value);
                    }
                })
                .print();


        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
